//package com.example.service.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.example.mapper.EmpMapper;
//import com.example.pojo.Emp;
//import com.example.pojo.Meeting;
//import com.example.mapper.MeetingMapper;
//import com.example.service.IMeetingService;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//
//import com.example.service.LoginService;
//import com.example.vo.ResultVo;
//import com.example.vo.respvo.EmpBasicInfoVo;
//import com.example.vo.respvo.meeting.HistMeetingVo;
//import com.example.vo.respvo.meeting.MeetingDetail;
//import com.example.vo.respvo.meeting.MeetingSignInTask;
//import com.example.vo.respvo.meeting.MeetingVo;
//import org.activiti.engine.HistoryService;
//import org.activiti.engine.RuntimeService;
//import org.activiti.engine.TaskService;
//import org.activiti.engine.history.HistoricProcessInstance;
//import org.activiti.engine.history.HistoricTaskInstance;
//import org.activiti.engine.history.HistoricTaskInstanceQuery;
//import org.activiti.engine.impl.identity.Authentication;
//import org.activiti.engine.runtime.ProcessInstance;
//import org.activiti.engine.task.Task;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletRequest;
//import java.text.DateFormat;
//import java.text.SimpleDateFormat;
//import java.time.Instant;
//import java.time.LocalDateTime;
//import java.time.ZoneId;
//import java.time.ZonedDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.*;
//
///**
// * <p>
// * 会议室使用申请表 服务实现类
// * </p>
// *
// * @author wsl
// * @since 2022-05-16
// */
//@Service
//public class MeetingServiceImpl extends ServiceImpl<MeetingMapper, Meeting> implements IMeetingService {
//
//    @Value("${process.key.meeting}")
//    private String processMeetingKey;
//
//    @Autowired
//    private RuntimeService runtimeService;
//
//    @Autowired
//    private TaskService taskService;
//
//    @Autowired
//    private HistoryService historyService;
//
//    @Autowired
//    private LoginService loginService;
//
//    @Autowired
//    private EmpMapper empMapper;
//
//    @Override
//    public ResultVo selectChamberPy() {
//        List<Meeting> list= baseMapper.selectChamberPy();
//        return ResultVo.response(list);
//    }
//
//    @Override
//    @Transactional
//    public ResultVo createMeeting(Meeting meeting, HttpServletRequest request) {
//        Integer userId = getCurrentUserId(request);
//        //1.新建会议流程
//        Date startDate = localDateTimeToDate(meeting.getStartTime());
//        Date endDate = localDateTimeToDate(meeting.getEndTime());
//
//        Map<String, Object> variables = new HashMap<>();
//        variables.put("host",meeting.getHost());
//        variables.put("people",meeting.getPeople());
//        variables.put("topic",meeting.getTopic());
//        variables.put("startTime",startDate);
//        variables.put("endTime",endDate);
//        Authentication.setAuthenticatedUserId(userId.toString());
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Meeting", variables);
//
//        //2.新增会议记录
//        meeting.setProcessId(processInstance.getId());
//        meeting.setPeopleNum(meeting.getPeople().size());
//        meeting.setPresentMember(JSON.toJSONString(meeting.getPeople()));
//        baseMapper.insert(meeting);
//        return ResultVo.response(meeting);
//    }
//
//    @Override
//    public ResultVo queryPersonalToDoTask(HttpServletRequest request) {
//        EmpBasicInfoVo loginUserInfo = loginService.getLoginUserInfo(request);
//        Integer empId = loginUserInfo.getId();
//        List<Task> taskList = taskService.createTaskQuery()
//                .taskAssignee(empId.toString())
//                .processDefinitionKey(processMeetingKey)
//                .list();
//        List<MeetingVo> meetingVos = new ArrayList<>();
//        taskList.forEach(task -> {
//            LocalDateTime endTime = DateToLocalDateTime((Date) taskService.getVariable(task.getId(), "endTime"));
//            LocalDateTime currentTime = LocalDateTime.now();
//            if(endTime.isAfter(currentTime)){
//                LocalDateTime startTime = DateToLocalDateTime((Date) taskService.getVariable(task.getId(), "startTime"));
//                MeetingVo meetingVo = new MeetingVo()
//                        .setTopic((String) taskService.getVariable(task.getId(), "topic"))
//                        .setHost((String) taskService.getVariable(task.getId(), "host"))
//                        .setPlace((String) taskService.getVariable(task.getId(), "place"))
//                        .setStartTime(startTime)
//                        .setEndTime(endTime)
//                        .setTaskId(task.getId())
//                        .setTaskName(task.getName())
//                        .setProcessInstanceId(task.getProcessInstanceId());
//                meetingVos.add(meetingVo);
//            }
//        });
//        return ResultVo.response(meetingVos);
//    }
//
//    @Override
//    public ResultVo queryPersonalUndoneTask(HttpServletRequest request) {
//        EmpBasicInfoVo loginUserInfo = loginService.getLoginUserInfo(request);
//        Integer empId = loginUserInfo.getId();
//        //1、查询没有完成的任务
//        List<HistoricTaskInstance> list = historyService
//                .createHistoricTaskInstanceQuery()
//                .unfinished()
//                .processDefinitionKey(processMeetingKey)
//                .taskAssignee(empId.toString())
//                .list();
//        List<Meeting> meetings = new ArrayList<>();
//        list.forEach(e->{
//            Date dueDate = e.getDueDate();
//            Date currentDate = new Date();
//            //2、只要未完成且过了期限的任务
//            if(!currentDate.before(dueDate)){
//                String processInstanceId = e.getProcessInstanceId();
//                Meeting meeting = baseMapper.selectOne(new QueryWrapper<Meeting>().eq("process_id", processInstanceId));
//                meetings.add(meeting);
//            }
//        });
//        return ResultVo.response(meetings);
//    }
//
//    @Override
//    public ResultVo queryProcessDetail(String processInstanceId) {
//        HistoricProcessInstance meetingProcessInstance = historyService
//                .createHistoricProcessInstanceQuery()
//                .processDefinitionKey(processMeetingKey)
//                .processInstanceId(processInstanceId)
//                .singleResult();
//        if(meetingProcessInstance==null){
//            return ResultVo.error("会议流程不存在！");
//        }else{
//            List<HistoricTaskInstance> taskInstances = historyService.createHistoricTaskInstanceQuery()
//                    .processInstanceId(processInstanceId)
//                    .list();
//            MeetingDetail meetingDetail = new MeetingDetail();
//            Meeting meeting1 = baseMapper.selectOne(new QueryWrapper<Meeting>().eq("process_id",processInstanceId));
//            meetingDetail.setTopic(meeting1.getTopic())
//                    .setEndTime(meeting1.getEndTime())
//                    .setStartTime(meeting1.getStartTime());
//            List<MeetingSignInTask> meetingSignInTasks = new ArrayList<>();
//            taskInstances.forEach(e->{
//                Emp emp = empMapper.selectOne(new QueryWrapper<Emp>().select("emp_name").eq("id", e.getAssignee()));
//                MeetingSignInTask meetingSignInTask = new MeetingSignInTask()
//                        .setAssignee(e.getAssignee())
//                        .setEmpName(emp!=null?emp.getEmpName():"")
//                        .setEndTime(e.getEndTime())
//                        .setIsHandle(e.getEndTime()!=null);
//                meetingSignInTasks.add(meetingSignInTask);
//            });
//            meetingDetail.setMeetingSignInTasks(meetingSignInTasks);
//            return ResultVo.response(meetingDetail);
//        }
//    }
//
//    @Override
//    public ResultVo completeMeetingSignInTask(String taskId) {
//        Task task = taskService.createTaskQuery()
//                .taskId(taskId)
//                .singleResult();
//        if(task!=null){
//            taskService.complete(task.getId());
//            return ResultVo.ok();
//        }
//        return ResultVo.error("任务没找到");
//    }
//
//    @Override
//    public ResultVo queryMyStartedMeeting(HttpServletRequest request) {
//        Integer userId = getCurrentUserId(request);
//        List<HistoricProcessInstance> list = historyService
//                .createHistoricProcessInstanceQuery()
//                .processDefinitionKey(processMeetingKey)
//                .startedBy(userId.toString())
//                .includeProcessVariables()
//                .list();
//        List<HistMeetingVo> meetingHisVo = new ArrayList<>();
//        list.forEach(e->{
//            Map<String, Object> processVariables = e.getProcessVariables();
//            HistMeetingVo histMeetingVo = new HistMeetingVo();
//            histMeetingVo.setEndTime(e.getEndTime());
//            histMeetingVo.setIsEnd(e.getEndTime()!=null);
//            histMeetingVo.setProcessInstanceId(e.getId());
//            histMeetingVo.setStartTime(e.getStartTime());
//            histMeetingVo.setUserId(e.getStartUserId());
//            histMeetingVo.setTopic((String)processVariables.get("topic"));
//            histMeetingVo.setHost((String)processVariables.get("host"));
//            meetingHisVo.add(histMeetingVo);
//        });
//        //1、查询我发起对会议
//        return ResultVo.response(meetingHisVo);
//    }
//
//    @Override
//    public ResultVo queryPersonalFinishedTask(HttpServletRequest request) {
//        EmpBasicInfoVo loginUser = loginService.getLoginUserInfo(request);
//        Integer empId = loginUser.getId();
//        List<HistoricTaskInstance> finishedMeetingTask = historyService.createHistoricTaskInstanceQuery()
//                .processDefinitionKey(processMeetingKey)
//                .taskAssignee(empId.toString())
//                .finished()
//                .list();
//        List<Map<String, Object>> finishedMeetingMap = new ArrayList<>();
//        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        finishedMeetingTask.forEach(task->{
//            String processInstanceId = task.getProcessInstanceId();
//            Map<String, Object> finishedMeeting = new HashMap<>();
//            Meeting meeting = baseMapper.selectOne(new QueryWrapper<Meeting>().eq("process_id", processInstanceId));
//            finishedMeeting.put("host",meeting.getHost());
//            finishedMeeting.put("topic",meeting.getTopic());
////            finishedMeeting.put("place",meeting.getPlace());
//            finishedMeeting.put("startTime",meeting.getStartTime().format(timeFormatter));
//            finishedMeeting.put("endTime",meeting.getEndTime().format(timeFormatter));
//            finishedMeeting.put("finishTime",format.format(task.getEndTime()));
//            finishedMeetingMap.add(finishedMeeting);
//        });
//        return ResultVo.response(finishedMeetingMap);
//    }
//
//    Date localDateTimeToDate(LocalDateTime localDateTime){
//        ZoneId zoneId = ZoneId.systemDefault();
//        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
//        Instant instant = zonedDateTime.toInstant();
//        return Date.from(instant);
//    }
//
//    LocalDateTime DateToLocalDateTime(Date date){
//        Instant instant = date.toInstant();
//        ZoneId zoneId = ZoneId.systemDefault();
//        return instant.atZone(zoneId).toLocalDateTime();
//    }
//
//    Integer getCurrentUserId(HttpServletRequest request){
//        EmpBasicInfoVo loginUserInfo = loginService.getLoginUserInfo(request);
//        return loginUserInfo.getId();
//    }
//}
